/* eslint-disable lines-between-class-members */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Card,  Calendar,InputNumber,Modal,Button,message} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import styles from './Pricefacilities.less';
const { Description } = DescriptionList;

@connect(({room, loading }) => ({
  room,
  loading: loading.effects['room/GetRoomPriceSetUp'],
}))
class BasicProfile extends Component {

  state={
    prices:[],
    visible: false,
    price:{},
    newPrice:0,
 
  };

  componentDidMount() {
    this.loadPriceInfo(moment().format("YYYY-MM"));
  }


  loadPriceInfo=(dateStr)=>{
    const root = this;
    const { dispatch,match:{params={}} } = root.props;
    const now0 = moment(dateStr).add(-1,"month");
    const now1 = moment(dateStr);
    const now2 = moment(dateStr).add(1,'month');
    if(params.id){

      //上一个月
      dispatch({
        type: 'room/GetRoomPriceSetUp',
        payload:{
          RoomId:params.id,
          Year:now0.format("YYYY"),
          Month:now0.format("MM"),
        },
        callback:response0=>{
          const {prices} = this.state;
          this.setState({
            prices:[...prices,...root.parsePrice(response0.result.months)],
          },function(){
           
          });
        }
      });

      //当月
      dispatch({
        type: 'room/GetRoomPriceSetUp',
        payload:{
          RoomId:params.id,
          Year:now1.format("YYYY"),
          Month:now1.format("MM"),
        },
        callback:response0=>{
          const {prices} = this.state;
          this.setState({
            prices:[...prices,...root.parsePrice(response0.result.months)],
          });
        }
      });

      //下月
      dispatch({
        type: 'room/GetRoomPriceSetUp',
        payload:{
          RoomId:params.id,
          Year:now2.format("YYYY"),
          Month:now2.format("MM"),
        },
        callback:response0=>{
          const {prices} = this.state;
          this.setState({
            prices:[...prices,...root.parsePrice(response0.result.months)],
          });
        }
      });
    }
  }

  getListData=(value)=>{
    const key = value.format("YYYY-MM-DD");
    let listData;
    listData = [
      {key, price: this.getPrice(key) },
    ];
    return listData || [];
  };

  getPrice=(key)=>{
    const {prices=[]} = this.state;
    const items = prices.filter(item=>item.key===key);
    if(items&&items.length>0){
      return items[0].price;
    }
    return 0;
  };

  dateCellRender=(value)=>{
    
    const listData = this.getListData(value);

    if(listData&&listData.length>0){
      const item = listData[0];
      return (
        <div>
          ￥ {item.price}
        </div>
      );
    }else {
      return 0;
    }
  };

  parsePrice=(monthsPrice)=>{
    let prices = [];
    for(let key in monthsPrice){
      prices = prices.concat(this.parseDatePrice(monthsPrice[key]));
    }
    return prices;
  };

  parseDatePrice=(prices)=>{
    return prices.map(item=>({
      key:moment(item.date).format("YYYY-MM-DD"),
      price:item.price
    }));
  };

  onSelect=(date)=>{
    this.setState({
      visible:true,
      price:{
        key:date.format("YYYY-MM-DD"),
        price:this.getPrice(date.format("YYYY-MM-DD"))
      }
    });
  };

  handleOk=()=>{
    const root = this;
    const { dispatch,match:{params={}} } = root.props;
    const {newPrice,price,prices} = this.state;
    if(newPrice==0||newPrice<0){
      if(price.price<0){
        message.error('价格不可低于0');
      }else{
        this.setState({
          visible:false,
          newPrice:0
        }); 
      }
    }else{
      dispatch({
        type:"room/SaveRoomPrice",
        payload: {
          RoomId:params.id,
          roomPrices:[{
            date:price.key,
            price:newPrice,
          }]
        },
        callback:response=>{
          if(response.success){
            message.success('价格调整成功');
            const newPrices = prices.map(item=>{
              if(item.key===price.key){
                item.price = newPrice
              }
              return item;
            });
            root.setState({
              prices:[...newPrices]
            })
          }else{
            message.error(response.error);
          }
        }
      });
      this.setState({
        visible:false,
        newPrice:0
      });
    }
   



  };
  handleCancel=()=>{
    this.setState({
      visible:false,
      newPrice:0,
    });
  };

  onChangePrice=(newPrice)=>{
    this.setState({
      newPrice,
    })
  };

  onChangeDate=(date)=>{

    this.loadPriceInfo(date.format("YYYY-MM"));
  };

  render() {
    const { room:{prices={}} , loading } = this.props;
    const {visible,price} = this.state;
    return (
      <PageHeaderWrapper title="房型价格" loading={loading}>
        <Card bordered={false} title='房价信息'>
        <DescriptionList size="large" title="房型信息" style={{ marginBottom: 2 }}>
            <Description term="房型名称">{prices.name}</Description>
            <Description term="基础价格（平日）">{prices.defaultPrice}</Description>
            <Description term="基础价格（周末）">{prices.weekendPrice}</Description>
          </DescriptionList>
        </Card>
        <br />
        <Card bordered={false} title='价格设置'>
          <Calendar
            defaultValue={moment()}
            onSelect={this.onSelect}
            onChange={this.onChangeDate}
            dateCellRender={this.dateCellRender}
          />
        </Card>
        <Modal
          title={<div style={{textAlign:'center'}}>{price.key}</div>}
          visible={visible}
          width={300}
          centered
          closable={false}
          footer={null}
          destroyOnClose
          maskClosable={false}
        >
          <p>现价：￥{price.price}</p>
          <p>修改为：<InputNumber onChange={this.onChangePrice} defaultValue={price.price} precision={2} style={{width:'70%'}} /></p>
          <div style={{textAlign:'center'}}>
            <Button onClick={this.handleOk} icon='check' style={{marginRight:32}}>修改</Button>
            <Button onClick={this.handleCancel}>取消</Button>
          </div>
        </Modal>
      </PageHeaderWrapper>
      
    );
  }
}

export default BasicProfile;
